<?php  if( !defined("IN_IA") ) 
{
	exit( "Access Denied" );
}
class Slwxkf_EweiShopV2Model
{
    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function __construct
     * @return null
     */
    function __construct()
    {
        $this->query = load()->object('query');
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 更新数据
     * @table string 表名
     * @update array data
     * @where array 条件
     * @return result(1 \\ false)
     */
    public function update($table = '', $update = '', $where = '')
    {
        $result = pdo_update('ewei_shop_'.$table, $update, $where);
        return $result;
    }
	
	/**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据会员id查找整个团队
     * @mid string 会员ID
     * @uniacid string 公众号ID
     * @return result(array,会员ID集合)
     */
    function getTeam($mid)
    {
        global $_W;
        global $_GPC;
        $team = array();
        //查找上级
        $topagent = $this->findUnlimitedAgent($mid);
        $team = array_merge($team,$topagent);
        //查找下级
        $members = $this->getInfoAll('member',array('uniacid' => $_W['uniacid'],'agentid !=' => 0),array('id','agentid'));
        $bottomagent = $this->findUnlimitedUnder($members,$mid);
        $team = array_merge($team,$bottomagent);
        //整个团队(上下级所有人)
        return $team;
    }
    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据会员id查找所有上级
     * @id string 会员ID
     * @return result(array,上级ID集合)
     */
    public function findUnlimitedAgent($id)
    {
        global $_W;
        global $_GPC;
        $topagent = array();
        $agent = pdo_fetch('select id,agentid,nickname from '.tablename('ewei_shop_member').' where id =:id and uniacid = :uniacid',array(':id'=>$id,':uniacid' => $_W['uniacid']));
        if (!empty($agent)) {

            $topagent[] = $agent['id'];

            if (!empty($agent['agentid'])) {
                $result = $this->findUnlimitedAgent($agent['agentid']);
                if (!empty($result)) {
                    $topagent = array_merge($topagent,$result);
                }
            }
        }
        return $topagent;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据会员id查找所有下级
     * @array array 此公众号下的会员集合
     * @pid string 当前会员id
     * @return result(array,下级ID集合)
     */
    function findUnlimitedUnder($array, $pid, $level = 0)
    {
        //声明静态数组,避免递归调用时,多次声明导致数组覆盖
        static $list = [];

        foreach ($array as $key => $value){
            //第一次遍历,找到父节点为根节点的节点 也就是agentid的节点
            if ($value['agentid'] == $pid){
                //父节点为根节点的节点,也就是第一级
                $value['level'] = $level;
                //把数组放到list中
                $list[] = $value['id'];
                //把这个节点从数组中移除,减少后续递归消耗
                unset($array[$key]);
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $this->findUnlimitedUnder($array, $value['id'], $level+1);
            }
        }
        $list = array_unique($list);
        return $list;
    }
	
    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 添加数据
     * @table string 表名
     * @insert array data
     * @return result(1 \\ false)
     */
    public function insert($table = '', $insert = '')
    {
        $result = pdo_insert('ewei_shop_'.$table, $insert);
        if (!empty($result)) {
            return pdo_insertid();
        }
        return $result;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 删除数据
     * @table string 表名
     * @where array 条件
     * @return result(int \\ false)
     */
    public function delete($table = '', $where = '')
    {
        $result = pdo_delete('ewei_shop_'.$table, $where);
        return $result;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据条件查找一条数据
     * @table string 表名
     * @where array 条件
     * @field array 查找字段
     * @return result(array,一维)
     */
    public function getInfo($table = '', $where = '', $field = '*')
    {
        if (empty($where)){
            $data = $this->query->from('ewei_shop_'.$table)->select($field)->get();
        }else{
            $data = $this->query->from('ewei_shop_'.$table)->where($where)->select($field)->get();
        }
        return $data;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据条件查找所有数据
     * @table string 表名
     * @where array 条件
     * @field array 查找字段
     * @return result(array,多维)
     */
    public function getInfoAll($table = '', $where = '', $field = '*')
    {
        if (empty($where)){
            $data = $this->query->from('ewei_shop_'.$table)->select($field)->getall();
        }else{
            $data = $this->query->from('ewei_shop_'.$table)->where($where)->select($field)->getall();
        }
        return $data;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据会员openid查找每个季度的订单
     * @openid string 会员openid
     * @uniacid string 公众号ID
     * @return result(string,订单总额)
     */
    public function secondaryDistribution($goods)
    {
        global $_W;
        //本会员
        $member = $this->getInfo('member',array('uniacid' => $_W['uniacid'],'id' => $_W['mid']));
        //上级第一代会员
        $member1 = $this->getInfo('member',array('uniacid' => $_W['uniacid'],'id' => $member['agentid']));
        if (!empty($member1)){
            if (!empty($goods)){
                foreach ($goods as $k=>$v) {
                    $commission = $this->getInfo('goods',array(['uniacid'] => $_W['uniacid'],'id' => $v['goodsid']),array('commission1_rate','commission1_pay','commission2_rate','commission2_pay'));
                    $price = $v['price'] * $v['total'];
                    //第一代返利
                    if ($commission['commission1_pay'] > 0){
                        $onefanli[$k] = $commission['commission1_pay'];
                    }else{
                        if ($commission['commission1_rate'] > 0){
                            $onefanli[$k] = $commission['commission1_rate'] * $price / 100;
                        }else{
                            $onefanli[$k] = 0;
                        }
                    }
                    //第二代返利
                    if ($commission['commission2_pay'] > 0){
                        $twofanli[$k] = $commission['commission2_pay'];
                    }else{
                        if ($commission['commission2_rate'] > 0){
                            $twofanli[$k] = $commission['commission2_rate'] * $price / 100;
                        }else{
                            $twofanli[$k] = 0;
                        }
                    }
                }
                $onefanliprice = array_sum($onefanli);
                $twofanliprice = array_sum($twofanli);
            }
            m('member')->setCredit($member1['openid'], 'credit2', $onefanliprice, array(0, '第一代购买返利:' . $onefanliprice));
            //上级第二代会员
            $member2 = $this->getInfo('member',array('uniacid' => $_W['uniacid'],'id' => $member1['agentid']));
            if (!empty($member2)){
                m('member')->setCredit($member2['openid'], 'credit2', $twofanliprice, array(0, '第二代购买返利:' . $twofanliprice));
            }
        }
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据会员openid查找每个季度的订单
     * @openid string 会员openid
     * @uniacid string 公众号ID
     * @return result(string,订单总额)
     */
    public function getAllPrice($openid,$uniacid)
    {
        $orders = $this->getInfoAll('order',array('openid' => $openid,'uniacid' => $uniacid),array('price','status','createtime'));
        if (!empty($orders)){
            foreach ($orders as $k=>$v){
                if ($v['status'] != -1 && $v['status'] != 0){
                    $data[$k] = $v;
                }
            }
            array_multisort(array_column($data,'createtime'),SORT_ASC,$data);
            $firsty = date('Y',$data[0]['createtime']);
            $firstm = date('m',$data[0]['createtime']);
            $nowy = date('Y',time());
            $nowm = date('m',time());
            $numm = $nowm - $firstm + ($nowy - $firsty) * 12;
            $number = $nowy - $firsty;
            if (!empty($data)){
                foreach ($data as $k=>$v) {
                    $data[$k]['y'] = date('Y',$v['createtime']);
                    $data[$k]['m'] = date('m',$v['createtime']);
                }
            }
            for ($i=0; $i <= $number; $i++){
                $list[$i] = $this->monthYear(($firsty + $i),$firstm,$data);
            }
            return $list;
        }
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据会员openid,返回年份季度结构
     * @openid string 会员openID
     * @uniacid string 公众号id
     * @return result(array,结构数据)
     */
    public function annualQuarter($openid,$uniacid)
    {
        $member = m("member")->getMember($openid, true);
        $list = $this->getAllPrice($openid,$uniacid);
        if (!empty($list)){
            foreach ($list as $k=>$v) {
                if (!empty($list[$k])){
                    foreach ($list[$k] as $k1=>$v1) {
                        $num = 0;
                        if (!empty($list[$k][$k1])){
                            foreach ($list[$k][$k1] as $k2=>$v2) {
                                $num += $v2['price'];
                            }
                        }
                        $list[$k][$k1]['price'] = $num;
                        $list[$k][$k1]['fanli'] = $this->selfPurchaseReturn($num);
                        $status = $this->getInfo('price_jidu',array('uniacid' => $uniacid,'openid' => $openid,'time' => ($list[0][0][0]['y'] + $k).'-'.($k1 + 1)));
                        if (empty($status)){
                            $list[$k][$k1]['status'] = 0;
                        }else{
                            $list[$k][$k1]['status'] = 1;
                        }
                    }
                }
            }
        }
        return $list;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 每笔订单按比例冲入奖池
     * @price string 订单金额
     * @return result(string,修改结果)
     */
    public function increaseRewardPool($price)
    {
        global $_W;
        $data = m('common')->getPluginset('fullownership');
        //奖池设置比例
        $proportion = $data['become_ordercount'];
        //获取奖池现有
        $jackpot = $data['jackpot'];
        //存入
        $update['jackpot'] = $jackpot + $proportion * $price / 100;
        $result = m('common')->updatePluginset(array('fullownership' => $update));
        return $result;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 每笔订单按比例冲入奖池
     * @price string 订单金额
     * @return result(string,修改结果)
     */
    public function bonus($id,$goods)
    {
        global $_W;
        $teams = $this->getTeamsLevel($id);
        //计算利润
        $range = $this->getRange($goods);
        foreach ($goods as $k=>$v) {
            foreach ($teams as $k1=>$v1) {
                if ($k1 < count($teams) - 1){
                    //判断是否脱离团队
                    if ($v1['agentlevel'] > $teams[($k1 + 1)]['agentlevel']){
                        //脱离团队

                    }else{
                        //正常逻辑关系
                        //1.判断与上级是平级
                        if ($v1['agentlevel'] == $teams[($k1 + 1)]['agentlevel']){
                            //平级:发平级奖
                        }
                    }
                }
            }
        }
        echo '<pre>';
        var_dump($goods);die;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 根据id返回团队成员详细信息
     * @id string 会员id
     * @return result(array,团队成员详细信息)
     */
    public function getTeamsLevel($id)
    {
        global $_W;
        $teams = $this->findUnlimitedAgent($id);
        foreach ($teams as $k=>$v) {
            $members[$k] = $this->getInfo('member',array('uniacid' => $_W['uniacid'],'id' => $v),array('agentlevel','id','openid'));
        }
        return $members;
    }

    /**
     * 索罗万象二次开发
     * 作者: @下雨吧จุ๊บ
     * @function 计算每笔订单利润
     * @goods array 所有商品
     * @return result(string,利润,价格)
     */
    public function getRange($goods)
    {
        if (!empty($goods)){
            $range = 0;
            foreach ($goods as $k=>$v) {
                $price = $v['price'] - $v['costprice'] * $v['total'];
                $range += $price;
            }
            return $range;
        }else{
            return 0;
        }
    }

}